package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IServiceItemService serviceItemService;




    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());

        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.insert(carPackageAudit);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateInstanceId(Long id, String instanceId) {
        carPackageAuditMapper.updateInstanceId(id,instanceId);
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        BpmnInfo bpmnInfo = bpmnInfoService.get(carPackageAudit.getBpmnInfoId());
        InputStream inputStream = null;
        //更加流程文件使用代码方式画出来
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            //审核中
            //根据流程定义id查询任务
            Task task = taskService.createTaskQuery()
                    .processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());
            inputStream = generator.generateDiagram(model, activeActivityIds,
                    Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }else {
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        //撤销条件
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (carPackageAudit==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("必须是在审核状态中才允许撤销");
        }
        //套餐服务状态修改为初始化
        serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        //套餐审核记录状态---撤销
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
        //审核实例删除
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"审核流程撤销");
    }

    //审批
    @Override
    public void audit(Long id, int auditStatus, String info) {
        //1.审批条件,carPackageAudit必须存在，状态是审核中
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (audit==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("状态必须是审批中才能审批");
        }
        String userName = ShiroUtils.getLoginName();
        String temp = audit.getAuditRecord() + "<br>";
        //约定：2 为同意
        if(auditStatus == 2){
            temp += "【"+userName+"同意】,备注"+info;
        }else{
            temp += "【"+userName+"拒绝】,备注"+info;
        }

        audit.setAuditRecord(temp);
        //流程审核记录表记录当前审核时间
        audit.setAuditTime(new Date());

        //执行当前节点,让流程跑到下一个节点
        Task task = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId()).singleResult();
        //设置审核中流程分支审核状态，auditStatus
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        //设置审核备注
        taskService.addComment(task.getId(),audit.getInstanceId(),temp);
        //执行节点审批
        taskService.complete(task.getId());
        //获取下一个节点
        Task nextTask = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId()).singleResult();
        //审核逻辑
        //审核通过
        if (auditStatus== CarPackageAudit.STATUS_PASS) {
            //如果有下一个节点
            if (nextTask!=null) {
                //流程审核记录表当前审核人-(财务),设置下一个审核人
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }else {
                //2>如果没有下一个节点- 流程结束
                //ServiceItem 状态变成审核通过
                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                //CarPackageAudit 状态变成审核通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        }else {
            //审核拒绝
            //ServiceItem状态变成初始化
            serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            // CarPackageAudit 状态变成 审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        //更新
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }

}
